// pages/shop/confirm/confirm.js
const call = require('../../utils/request.js')
const Util = require( '../../utils/util.js' );
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    sumPrice:"0.00", //商品总价
    fee: "0.00", //邮费
    sumLast: "0.00", //最后总价
    notVipProduct: true, //是否不包含vip套餐
    send:0, //用途选择 自用0 送礼1
    phone: '', //受礼人电话
    remark: '', //备注
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获取地址
    this.getAddressList(); 
    //获取订单和邮费，判断是否包含vip套餐
    const list = app.globalData.goodsList
    let notVipProduct = true;
    let fee = 0;
    for(let i in list){
      fee += parseFloat(list[i].ship_fee_template.fee);
      if(list[i].is_vip_product == 1){notVipProduct = false;}
    }

    fee = fee.toFixed(2)
    this.setData({
      list,
      fee,
      notVipProduct
    })
    //获取总价
    this.getSumPrice();
    this.getLastSum(); 
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 输入框绑定 
   */
  bindInput(e){
    const name = e.currentTarget.dataset.name;
    this.setData({
      [`${name}`]:e.detail.value
    })
  },

  /**
   * 用途选择
   */
  chooseSend(e){
    const type = e.currentTarget.dataset.type;
    this.setData({
      send:type
    })
  },

  /**
   * 获取收获地址
   */
  getAddressList(){
    wx.showLoading({
      title: '正在获取地址',
      mask:true
    })
    call.post('/api/home/address_index').then(res=>{
      console.log("获取地址列表",res)
      let data = {};
      if(res.data.data.list.length>0){
        data = res.data.data.list[0]
      }
      this.setData({
        address: data
      })
      wx.hideLoading();
    })
  },

  /**
   * 获取商品总价
   */
  getSumPrice(){
    const list = this.data.list;
    let price = 0;
    for(let i of list){
      price += parseFloat(i.count * i.price)
    }
    price = price.toFixed(2);
    this.setData({
      sumPrice:price
    })
  },

  /**
   * 获取最后总价，含运费
   */
  getLastSum(){
    const list = this.data.list;
    const adrId = this.data.address?this.data.address.id:0;
    let goods_list = [];
    for(let i of list){
      goods_list.push({
        goods_id: i.product_id,
        goods_specific_id: i.product_spec_id,
        count: i.count,
        is_vip_product: i.is_vip_product,
        is_gift: 0,
        phone: '',
      })
    }
    let data = {
      goods_list:goods_list,
      discount_coupon_id:0,
      remark:''
    }

    wx.showLoading({
      title: '正在获取总价',
      mask:true
    })
    call.post('/api/shop/calc_order_amount',JSON.stringify(data)).then(res=>{
      console.log("获取订单总价",res)
      this.setData({
        sumLast: res.data.data
      })
      wx.hideLoading();
    })
    
  },

  /**
   * 地址跳转
   */
  toUrl(e){
    const url = e.currentTarget.dataset.url;
    wx.navigateTo({
      url: url,
    })
  },

  /**
   * 提交订单
   */
  submit(){
    const list = this.data.list;
    const adrId = this.data.address.id?this.data.address.id:0;
    //判断是否有填写地址
    if(adrId == 0){
      wx.showToast({
        title: '请选择收货地址',
        icon: 'none'
      })
      return;
    }

    let goods_list = [];
    for(let i of list){
      let data = {
        goods_id: i.product_id,
        goods_specific_id: i.product_spec_id,
        count: i.count,
        is_vip_product: i.is_vip_product,
        is_gift: this.data.send,
        phone: this.data.phone,
      };
      if(i.cart_id){
        data = Object.assign(data,{
          cart_id:i.cart_id
        })
      }
      goods_list.push(data)
    }
    let data = {
      goods_list:goods_list,
      addr_id: adrId,
      discount_coupon_id:0,
      remark:this.data.remark
    }
    wx.showLoading({
      title: '正在提交订单',
      mask:true
    })
    call.post('/api/shop/generate_order',JSON.stringify(data)).then(res=>{
      wx.hideLoading();
      console.log("提交订单",res)
      const res1 = res.data.data;
      if(res.statusCode == 200 && res.data.code == 0){
        wx.requestPayment({
          timeStamp: res1.timeStamp,
          nonceStr: res1.nonceStr,
          package: res1.package,
          signType: res1.signType,
          paySign: res1.paySign,
          success:(res)=> { 
            console.log("调用成功")
            if(!this.data.notVipProduct && app.globalData.vip == 0){
              app.globalData.vip = 1;
              let user = wx.getStorageSync('user');
              user.vip = 1;
              wx.setStorageSync('user', user)
            }
            wx.showLoading({
              title: '正在跳转',
              mask: true
            })
            setTimeout(function(){
              wx.navigateTo({
                url: '../../my/orderlist/orderList?delta=2',
              })
            },2000)
          },
          fail :(res)=> { 
            console.log("调用失败")
            wx.navigateTo({
              url: '../../my/orderlist/orderList?delta=2',
            })
          }
        })
      }
    })
  },
})